<template>
  <!-- 特行证信息 / 详情 / 完善特行证信息 -->
  <view class="tradeLicense">
    <view class="wrapper">
      <view class="wrapper-item content" :class="orFlag == 3 ? 'detailOrflag' : ''">
        <block v-if="orFlag == 1 || orFlag == 2">
          <u-form :model="form" ref="form" label-width="100" :error-type="errorType">
            <u-form-item label="证件图片" label-width="70">
              <text style="color: #a1a1a1; font-size: 26rpx">
                (大小2M以内)
              </text>
            </u-form-item>
            <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic(2)" name="file" :maxCount="1"
              width="310" height="180">
              <image :src="baseImgUrl + 'card_2.png'" style="width: 640rpx; height: 430rpx"></image>
            </u-upload>
            <u-form-item label="证书编码" label-width="70">
              <view class="special-class">
                <view>
                  <u--input v-model.trim="form.ccieFirst" border="bottom" :maxlength="2"></u--input>
                  <span>公特</span>
                </view>
                <view>
                  <u--input v-model.trim="form.ccieSecond" border="bottom" :maxlength="2"></u--input>
                  <span>字第</span>
                </view>
                <view>
                  <u--input v-model.trim="form.ccieThird" border="bottom" :maxlength="8"></u--input>
                  <span>号</span>
                </view>
              </view>
            </u-form-item>
            <u-form-item label="发证机关" borderBottom label-width="70">
              <u--input v-model.trim="form.certificateOffice" border="none" placeholder="请填写"
                :maxlength="18"></u--input>
            </u-form-item>

            <u-form-item label="发证日期" borderBottom label-width="70" @click="cellTimeClick('certificateDate')">
              <u--input v-model="form.certificateDateName" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>
              <image :src="baseImgUrl + 'day-icon.png'" mode="" slot="right" class="seleTime"></image>
            </u-form-item>
          </u-form>
        </block>
        <block v-if="orFlag == 3">
          <u-form-item label="证件图片" label-width="70">
            <text style="color: #a1a1a1; font-size: 26rpx"> (大小2M以内) </text>
          </u-form-item>
          <image :src="imgPrefix + form.certificateUrl" mode="aspectFill" style="width: 640rpx; height: 430rpx"
            @click="pvwImage([imgPrefix + form.certificateUrl])"></image>

          <u-form-item label="证书编码" label-width="70">
            <view class="special-class">
              <view>
                <u--input v-model.trim="form.ccieFirst" border="bottom" readonly></u--input>
                <span>公特</span>
              </view>
              <view>
                <u--input v-model.trim="form.ccieSecond" border="bottom" readonly></u--input>
                <span>字第</span>
              </view>
              <view>
                <u--input v-model.trim="form.ccieThird" border="bottom" readonly></u--input>
                <span>号</span>
              </view>
            </view>
          </u-form-item>
          <u-form-item label="发证机关" borderBottom label-width="70">
            <u--input v-model.trim="form.certificateOffice" border="none" readonly></u--input>
          </u-form-item>

          <u-form-item label="发证日期" borderBottom label-width="70">
            <u--input v-model="form.certificateDateName" disabled disabledColor="#ffffff" border="none"
              readonly></u--input>
          </u-form-item>
        </block>
      </view>
    </view>

    <view class="btns thispageBtn" v-if="options.companyStatus != 3 && orFlag != 3">
      <block v-if="orFlag == 1 || orFlag == 2">
        <button class="cancel-btn lt" type="primary" @click="navBack('back', 1, 1)">
          取消
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          保存
        </button>
      </block>
      <!-- <button
        v-if="orFlag == 3"
        class="submit-btn"
        type="primary"
        @click="editHandle"
        icon="map"
        style="width: 100%"
      >
        修改
      </button> -->
    </view>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date" :formatter="formatter"
      :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose" @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
  </view>
</template>

<script>
  import {
    certificateDetail,
    smartStructuralOrc,
    certificateSave,
  } from "@/api/myself.js";
  import mixin from "@/utils/mixin.js";
  import {
    Toast,
    navBack,
    uniTrim,
    formatters,
    dayTurnTime,
    pvwImage,
    getBase64Two,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";

  export default {
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        options: {},
        form: {},
        errorType: ["none"],
        orFlag: 1, // 1：添加   2：编辑  3：详情
        fileList: [],
        imgPrefix: uni.getStorageSync("imgPrefix"),
      };
    },
    onLoad(options) {
      this.options = options;

      if (options.certificateStatus == 0 && options.companyStatus != 3) {
        uni.setNavigationBarTitle({
          title: "完善特行证信息",
        });
      }

      if (options.certificateStatus != 0) {
        this.orFlag = 3;
        certificateDetail({
          companyId: options.id
        }).then((res) => {
          let {
            certificateCodeList,
            certificateUrl,
            certificateTime
          } =
          res.result;
          this.form = res.result;
          this.form.ccieFirst = certificateCodeList[0] || "";
          this.form.ccieSecond = certificateCodeList[1];
          this.form.ccieThird = certificateCodeList[2];
          this.form.certificateDateName = formatters(certificateTime, "YY/MM/DD");
          this.form.certificateDate = dayTurnTime(this.form.certificateDateName);
          this.fileList.push({
            url: this.imgPrefix + certificateUrl,
          });
        });
      }
    },
    methods: {
      navBack,
      pvwImage,
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        this.cellType = e;
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "certificateDate":
            this.maxDate = minDateNum;
            this.timeValue = this.maxDate;
            break;
          default:
            break;
        }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "certificateDate":
              this.form.certificateDate = "";
              this.form.certificateDateName = "";
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "certificateDate":
              this.form.certificateDateName = formatters(arr, "YY/MM/DD");
              this.form.certificateDate = dayTurnTime(
                this.form.certificateDateName
              );
              break;

            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      afterRead(info) {
        let _this = this;
        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            smartStructuralOrc({
              imageBase64: res
            }).then((res) => {
              if (res.code != 200) return Toast("请上传正确的特种行业许可证");

              var ocrList = res.result.structuralItems;
              var indexName = ocrList.map((v) => v.name).indexOf("标题");
              var indexvalue = ocrList
                .map((v) => v.value)
                .indexOf("特种行业许可证");

              if (indexName != -1 && indexvalue != -1) {
                _this.ocrPicHandle(ocrList, info.file.url);
                return;
              }

              Toast("请上传正确的特种行业许可证");
            });
          });
      },
      ocrPicHandle(ocrList, urlimg) {
        ocrList.map((v) => {
          if (v.name == "证字号") {
            let nameV = v.value;
            let gt = nameV.lastIndexOf("公特");
            let zd = nameV.lastIndexOf("字第");
            let num = nameV.lastIndexOf("号");

            let firsta = nameV.slice(0, nameV);
            let firsts = nameV.slice(gt + 2, zd);
            let firstt = nameV.slice(zd + 2, num);
            this.$set(this.form, "ccieFirst", firsta || "");
            this.$set(this.form, "ccieSecond", firsts || "");
            this.$set(this.form, "ccieThird", firstt);
          }

          if (v.name == "日期") {
            let year = v.value.lastIndexOf("年");
            let month = v.value.lastIndexOf("月");
            let day = v.value.lastIndexOf("日");

            var da1 = v.value.slice(0, year); //年
            var da2 = v.value.slice(year + 1, month); // 月
            var da3 = v.value.slice(month + 1, day); // 日
            let gTime = dayTurnTime(`${da1}/${da2}/${da3}`);
            this.form.certificateDateName = formatters(gTime, "YY/MM/DD");
            this.form.certificateDate = gTime;
          }
        });

        let _this = this;
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: urlimg,
            name: "file",
            formData: {
              type: 17,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList.push({
              url: fullPath
            });
            _this.form.certificateUrl = halfPath;
          })
          .finally(() => {})
      },
      deletePic() {
        this.fileList = [];
        this.form.certificateUrl = "";
      },
      editHandle() {
        this.orFlag = 2;
      },
      submitHandle() {
        let {
          ccieFirst,
          ccieSecond,
          ccieThird,
          certificateOffice,
          certificateDate,
          certificateUrl,
        } = this.form;
        if (!certificateUrl) {
          Toast("请上特殊行业许可证照片");
          return;
        }

        if (!ccieThird || !uniTrim(ccieThird)) {
          Toast("请输入证书编码");
          return;
        }

        if (!certificateOffice || !uniTrim(certificateOffice)) {
          Toast("请输入发证机关");
          return;
        }

        if (!certificateDate || !uniTrim(certificateDate)) {
          Toast("请选择发证日期");
          return;
        }

        let data = {
          companyMessageId: this.options.id,
          certificateCodeList: [ccieFirst || "", ccieSecond || "", ccieThird],
          certificateOffice,
          certificateDate,
          certificateUrl,
        };

        certificateSave(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            navBack("back", 2);
            return;
          }
          Toast(res.message);
        });
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .tradeLicense {
    flex: 1;
    background-color: #f3f3f3;

    .tradeLicense-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 20rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 702rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }

      .detailOrflag {
        height: calc(100vh - 30px);
      }
    }

    .special-class {
      display: flex;

      view {
        width: 160rpx;
        display: flex;

        /deep/.u-input {
          width: 60% !important;
        }
      }

      view:nth-of-type(3) {
        width: 205rpx;
      }

      /deep/input {
        padding-right: 0;
      }

      span {
        padding-top: 18rpx;
        font-size: 30rpx;
      }
    }

    .seleTime {
      width: 45rpx;
      height: 45rpx;
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }
  }
</style>